/**************************************************************************
 *
 * Copyright (C) 2007 University of California, Los Angeles.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 *************************************************************************/

package edu.ucla.cs.typecast.rmi.server;

import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

import edu.ucla.cs.typecast.bloomfilter.BloomFilter;
import edu.ucla.cs.typecast.bloomfilter.BloomFilterEncoder;
import edu.ucla.cs.typecast.net.EndPoint;
import edu.ucla.cs.typecast.net.EndPointListener;
import edu.ucla.cs.typecast.rmi.MethodInvocation;
import edu.ucla.cs.typecast.util.TypeUtil;

/**
 * 
 * This class manages all the TypeCast service objects bound to a specific network end point. 
 * @date Jul 25, 2007
 *
 */
public  class TypeCastServiceRegistrar {

	private EndPoint endPoint; 
	private Hashtable<Class, Vector<ServiceRegistrationEntry>> registration = new Hashtable<Class, Vector<ServiceRegistrationEntry>>(); 
	private Hashtable<Object, HashSet<Class>> objectMap = new Hashtable<Object,HashSet<Class>>(); 
	private EndPointListener endPointListener; 
	private BloomFilter LBF; 

	/**
	 * Constructor
	 * @param endPoint The network end point via which the services will be exported. 
	 * @param listener The EndPointListener managing the network end point. 
	 * 
	 */
	public TypeCastServiceRegistrar(EndPoint endPoint, EndPointListener listener) { 
		this.endPoint = endPoint; 
		this.endPointListener = listener; 
	}
	
	public synchronized void exportService(Class[] types, Object serviceObject) throws IOException { 
		for(int i=0; i<types.length; i++ ) { 
			if (!types[i].isInterface()) { 
				throw new RuntimeException(types[i] + " must be interface in order to export"); 
			}
			if ( (types[i].getModifiers() & Modifier.PUBLIC ) == 0) { 
				throw new RuntimeException(types[i] + " must be public interface in order to export"); 
			}
 			if (! (types[i].isInstance(serviceObject))) { 
				throw new RuntimeException(serviceObject + " is not type " + types[i]); 
			}
		}
		
		ServiceRegistrationEntry entry = new ServiceRegistrationEntry(this.endPoint, types, serviceObject); 
		Collection<Class> allTypes = TypeUtil.getAllTypes(types); 
		for(Class type: allTypes) { 
			Vector<ServiceRegistrationEntry> v = registration.get(type); 
			if (v == null) { 
				v = new Vector<ServiceRegistrationEntry>(); 
				registration.put(type, v); 
			}
			if (!v.contains(entry)) { 
				v.add(entry); 
			}
		}
		
		HashSet<Class> set = objectMap.get(serviceObject); 
		if (set == null) { 
			set = new HashSet<Class>(); 
			objectMap.put(serviceObject, set); 
		}
		set.addAll(allTypes); 
		
		if (objectMap.size() == 1) { 
			endPointListener.activate(endPoint); 
			LBF = getLBF(); 
			endPointListener.update(endPoint, LBF); 
		}  else { 			
			LBF = getLBF(); 
			endPointListener.update(endPoint, LBF); 
		}
		
		
	}
	
	public void exportService(Class type, Object object) throws IOException { 
		exportService(new Class[]{type}, object); 
	}
	
	public synchronized void unexportService(Object serviceObject) throws IOException { 
		HashSet<Class> types = objectMap.get(serviceObject); 
		if (types != null) { 
			Iterator<Class> iter = types.iterator(); 
			while(iter.hasNext()) { 
				Class type = iter.next(); 
				Vector<ServiceRegistrationEntry> entries = registration.get(type); 
				if (entries != null) { 
					Vector<ServiceRegistrationEntry> v =  new Vector<ServiceRegistrationEntry>(); 
					for(int i=0; i<entries.size(); i++) { 
						ServiceRegistrationEntry entry = entries.elementAt(i); 
						if (!entry.getService().equals(serviceObject)) { 
							v.add(entry); 
						}
					}
					if (v.size() == 0) { 
						registration.remove(type); 
					} else { 
						registration.put(type, v); 
					}
				}
			}
		}
		objectMap.remove(serviceObject); 
		LBF = getLBF(); 
		endPointListener.update(endPoint, LBF); 
		if (registration.isEmpty()) { 
			endPointListener.deactivate(endPoint); 
		}
	}
	
	/**
	 * Get the Local Bloom filter that encodes all the registered types. 
	 * @return
	 */
	public synchronized BloomFilter getLBF() { 
		return BloomFilterEncoder.encode(registration.keySet()); 
	}
	/**
	 * Get all the TypeCast service objects that matchs a
	 * method invocation. 
	 * @param invocation 
	 * @return
	 */
	public Collection getServices(MethodInvocation invocation) { 
		Class primaryType = invocation.getMethod().getDeclaringClass(); 
		Vector<ServiceRegistrationEntry> v = registration.get(primaryType); 
		if (v == null) {
			return Collections.EMPTY_LIST; 
		}
		HashSet<Object> services = new HashSet<Object>(); 
		Vector<ServiceRegistrationEntry> entries = (Vector<ServiceRegistrationEntry>)v.clone(); 
		Iterator<ServiceRegistrationEntry> iter = entries.iterator(); 
		while(iter.hasNext()) { 
			ServiceRegistrationEntry entry = iter.next(); 
			if (entry.match(invocation.getTypes())) { 
				services.add(entry.getService()); 
			}
		}
		return services; 
	}

	/**
	 * Get all the service objects that implement a specific type
	 * @param type
	 * @return
	 */
	public Collection getServices(Class type) { 
		Vector<ServiceRegistrationEntry> v = registration.get(type); 
		if (v == null) {
			return Collections.EMPTY_LIST; 
		}
		Vector<ServiceRegistrationEntry> entries = (Vector<ServiceRegistrationEntry>)v.clone(); 
		HashSet services = new HashSet(); 
		for(ServiceRegistrationEntry entry : entries) { 
			services.add(entry.getService()); 
		}
		return services; 	
	}
	
	/**
	 * Get all the service registration entries that implements specific types
	 * @param types
	 * @return
	 */
	public Collection<ServiceRegistrationEntry> getServiceRegistrationEntries(Class[] types) { 
		Vector<ServiceRegistrationEntry> v = registration.get(types[0]); 
		if (v == null) {
			return Collections.EMPTY_LIST; 
		}
		HashSet<ServiceRegistrationEntry> result = new HashSet<ServiceRegistrationEntry>(); 
		Vector<ServiceRegistrationEntry> entries = (Vector<ServiceRegistrationEntry>)v.clone(); 
		Iterator<ServiceRegistrationEntry> iter = entries.iterator(); 
		while(iter.hasNext()) { 
			ServiceRegistrationEntry entry = iter.next(); 
			if (entry.match(types)) { 
				result.add(entry);
			}
		}
		return result; 			
	}
	
	public Set<Class> getExportedTypes(Object serviceObject) { 
		return objectMap.get(serviceObject); 
	}
}
